import { getProfile, updateUserInfo, updateUserPhoto } from '../../api/user'

export default {
  namespaced: true,
  state: {
    userInfo: {}
  },
  mutations: {
    mSetUserInfo (state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 姓名
    mUpdateUserName (state, newName) {
      state.userInfo.name = newName
    },
    // 性别
    mUpdateUserGender (state, gender) {
      state.userInfo.gender = gender
    },
    // 生日
    mUpdateUserBirthday (state, newBirthday) {
      state.userInfo.birthday = newBirthday
    },
    mUpdateUserPhoto (state, newPhoto) {
      state.userInfo.photo = newPhoto
    }
  },
  actions: {
    async getProfile (context) {
      try {
        const res = await getProfile()
        console.log('modules,getProfile', res)
        context.commit('mSetUserInfo', res.data.data)
      } catch (err) {
        console.log(err)
        throw new Error(err)
      }
    },
    async updateUserName (context, newName) {
      try {
        await updateUserInfo({ name: newName })
        context.commit('mUpdateUserName', newName)
      } catch (err) {
        console.log(err)
        throw new Error(err)
      }
    },
    async updateUserGender (context, gender) {
      try {
        await updateUserInfo({ gender })
        context.commit('mUpdateUserGender', gender)
      } catch (err) {
        console.log(err)

        throw new Error(err)
      }
    },
    async updateUserBirthday (context, birthday) {
      try {
        await updateUserInfo({ birthday })
        context.commit('mUpdateUserBirthday', birthday)
      } catch (err) {
        console.log(err)
        throw new Error(err)
      }
    },
    // async updateUserPhoto (context, fd) {
    //   try {
    //     await updateUserInfo({ fd })
    //     context.commit("mUpdateUserPhoto", fd)
    //   } catch (err) {
    //     console.log(err)
    //     throw new Error(err)
    //   }
    // }

    // 修改头像
    async updateUserPhoto (context, fd) {
      try {
        const res = await updateUserPhoto(fd)
        console.log('updateUserPhoto', res)
        context.commit('mUpdateUserPhoto', res.data.data.photo)
      } catch (err) {
        console.log(err)
        throw new Error(err)
      }
    }
  }
}
